import { CookieOptions, CookieRef, useCookie } from "#app";
import { computed, ref } from "vue";
import { parse, serialize } from "cookie-es";

export default ((): typeof useCookie<string> => {
  if (import.meta.env.SSR) {
    return useCookie;
  } else {
    const cache = new Map<string, CookieRef<string>>();
    return (name: string, _opts?: CookieOptions<string>) => {
      if (!cache.has(name)) {
        cache.set(
          name,
          ref((<Record<string, string>>parse(document.cookie))[name] || "")
        );
      }
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      const cookieRef = cache.get(name)!;
      return computed({
        get: () => cookieRef.value,
        set: v => {
          cookieRef.value = v;
          document.cookie = serialize(name, v, _opts);
        }
      });
    };
  }
})();
